#include "threadPool.h"
#include <ctype.h>
char **split_words(char *str, int *count)
{
    int i, j, k;
    char **words = NULL;
    char *word = NULL;
    *count = 0;
    i = j = 0;
    while (str[i])
    {
        while (isspace(str[i]))
            i++; // skip leading spaces
        j = i;
        while (!isspace(str[j]) && str[j])
            j++; // find end of word
        if (j > i)
        {                                              // if word found
            word = malloc(sizeof(char) * (j - i + 1)); // allocate memory for word
            if (!word)
            { // check if allocation failed
                for (k = 0; k < *count; k++)
                    free(words[k]); // free memory allocated for previous words
                free(words);        // free memory allocated for word pointers
                *count = 0;         // reset count
                return NULL;        // return NULL
            }
            strncpy(word, str + i, j - i);                     // copy word
            word[j - i] = '\0';                                // add null terminator
            (*count)++;                                        // increment count
            words = realloc(words, sizeof(char *) * (*count)); // allocate memory for new word pointer
            words[*count - 1] = word;                          // add word pointer to array
        }
        i = j + 1; // move to next word
    }
    return words;
}

int makeWorker(threadPool_t *pthreadPool)
{
    for (int i = 0; i < pthreadPool->threadNum; ++i)
    {
        pthread_create(pthreadPool->tidArr + i, NULL, threadFunc, pthreadPool);
    }
}
void cleanMutex(void *pargs)
{
    threadPool_t *pthreadPool = (threadPool_t *)pargs;
    pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
}
#define WORD_LEN_MAX 20
void *threadFunc(void *pargs)
{
    // 子线程相关的函数
    threadPool_t *pthreadPool = (threadPool_t *)pargs;
    // 执行具体业务
    while (1)
    {
        // 取出任务
        int netfd;
        //tail -f /var/log/syslog 实时查看syslog
        pthread_mutex_lock(&pthreadPool->taskQueue.mutex);
        // pthread_cleanup_push(cleanMutex,pthreadPool);
        if (pthreadPool->isexit == 1)
        {
            printf("I am going to exit!\n");
            log_INFO("I am going to exit!");
            pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
            pthread_exit(NULL);
        }

        while (pthreadPool->taskQueue.queueSize == 0)
        {
            pthread_cond_wait(&pthreadPool->taskQueue.cond, &pthreadPool->taskQueue.mutex);
            if (pthreadPool->isexit == 1)
            {
                printf("I am going to exit!\n");
                 log_INFO("I am going to exit!");
                pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
                pthread_exit(NULL);
            }
        }
        printf("child thread got task!\n");
         log_INFO("child thread got task!");
        netfd = pthreadPool->taskQueue.pFront->netfd; // 把队首的数据域取出来
        taskDeQueue(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
        // pthread_cleanup_pop(1);
        //  执行任务
        // 接受信息
        pthreadPool->netfd=netfd;
        int bufLen = 0 ;
	    int recvRet ;
        while (1)
        {
            bzero(pthreadPool->buf, sizeof(pthreadPool->buf));
            recvRet = recv(netfd, &bufLen, sizeof(int), 0); // 收到客户端的火车头
            if (bufLen == 0 || recvRet == 0)
            {
                printf("client exit !\n");
                log_INFO("client exit !");
                close(netfd);
                break;
            }
            recvn(netfd, pthreadPool->buf, bufLen);//收火车车厢
            int count, i;
            char **words = split_words(pthreadPool->buf, &count);
            // 处理命令
            if (1 == count)
            {
                if (strcmp(words[0], "pwd") == 0)
                {
                    pwd(pthreadPool);
                }
                else{
                    log_ERROR("Invalid command received from client.");
                }

            }
            if (2 == count)
            {
                strcpy(pthreadPool->buf,words[1]);
                if (strcmp(words[0], "cd") == 0)
                {
                    myChdir(pthreadPool);
                }
                else if (strcmp(words[0], "gets") == 0)
                {
                    printf("start transFile\n");
                    transFile(netfd, pthreadPool->buf);
                    printf("transFile finished\n");
                }
                else if (strcmp(words[0], "puts") == 0)
                {
                    printf("start recvFile\n");
                    recvFile(netfd);
                    printf("recvFile finished\n");
                }
                else if (strcmp(words[0], "ls") == 0)
                {
                    ls(pthreadPool);
                }
                else if (strcmp(words[0], "remove") == 0)
                {
                    reMove(pthreadPool);
                }else{
                    printf("Invalid command received from client.\n");
                    log_ERROR("Invalid command received from client.");
                }
            }
            // 释放空间
            for (i = 0; i < count; i++)
            {
                free(words[i]);
            }
            free(words);
        }
        // transFile(netfd);
        close(netfd);
        // 恢复空闲
        printf("child thread finished task!\n");
        log_INFO("child thread finished task!");
    }
}